<template>
<a-spin tip="Loading..." :spinning="spinning">
  <a-row>
    <a-card>
      <a-row>
        <a-col span="9">
         
            <a-button style="margin-right:8px" type="primary" @click="showModal">录入数据</a-button>
            <a-button style="margin-right:8px" type="primary" @click="export_se">导出抄表单</a-button>
            <!--<a-button style="margin-right:8px" type="primary" @click="exportModal">导出抄表单</a-button>-->
            <a-button style="margin-right:8px" type="primary" @click="() => { $router.push({name:'charge_copy_table_import'})}">导入抄表单</a-button>
            <!-- <a-button style="margin-right:8px" disabled>删除</a-button> -->
        </a-col>
        <a-col span="8" offset="7">
          <a-row type="flex" justify="space-around">
            <a-col span="18">
              <a-input-search placeholder="请输入房号" @search="onSearch"></a-input-search>
            </a-col>
            <a-col span="2">
              <a-button @click="searchModal">
                <a-icon type="filter" />
              </a-button>
            </a-col>
          </a-row>
        </a-col>
        <!-- 弹出层 -->
        <a-modal
          title="导出抄表单"
          :visible="exportVisible"
          @ok="exportOk"
          @cancel="exportCancel"
        >
          <a-row>
            <a-form>
              <a-col span="24">
                <a-form-item label="小区" :label-col="labelCol" :wrapper-col="wrapperCol">
                  <a-select placeholder="请选择所属小区" v-decorator="['bd_info_id',{rules:[{required:true,message:'请选择小区'}]}]">
                    <a-select-option v-for="(item,index) in bd_info" @click="bdPro(index)" :key="index" :value="item.id">{{item.name}}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col span="24">
                <a-form-item label="收费项目" :label-col="labelCol" :wrapper-col="wrapperCol">
                  <a-select placeholder="请选择收费项目" v-decorator="['project',{rules:[{required:true,message:'请选择收费项目'}]}]">
                    <a-select-option v-for="(item,index) in tollProject" @click="detPro(index)" :key="index" :value="item.value">{{item.label}}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col span="24">
                <a-form-item label="收费标准" :label-col="labelCol" :wrapper-col="wrapperCol">
                  <a-select placeholder="请选择收费标准" v-decorator="['project',{rules:[{required:true,message:'请选择收费标准'}]}]">
                    <a-select-option v-for="(item,index) in proList" @click="setPro(index)" :key="index" :value="item.value">{{item.label}}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-form>
          </a-row>
        </a-modal>
        <a-modal
                title="确认窗口"
                :visible="show_se"
                @ok="exportOk1"
                @cancel="export_se_cel"
        >
          <span v-for="(item,index) in qu_s" :key="index" style="padding: 3px;font-size: 16px">{{item}}<br /></span>
        </a-modal>
        <a-modal
          title="高级搜索"
          :visible="searchVisible"
          @ok="searchOk"
          :confirmLoading="confirmLoading"
          @cancel="searchCancel"
        >
          <a-row>
            <a-form>
              <a-col span="24">
                <a-form-item label="小区" :label-col="labelCol" :wrapper-col="wrapperCol">
                  <a-select placeholder="请选择小区">
                    <a-select-option v-for="(item,index) in bd_info" :key="index" :value="item.id" @click="bd_click(item.id)">{{item.name}}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col span="24">
                <a-form-item label="项目/标准" :label-col="labelCol" :wrapper-col="wrapperCol">
                  <a-cascader :options="options1" placeholder="请选择收费项目/标准" @change="selectProject"/>
                </a-form-item>
              </a-col>
              <a-col span="24">
                <a-form-item label="开始/结束时间" :label-col="labelCol" :wrapper-col="wrapperCol">
                  <a-form-item
                    :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }"
                  >
                    <a-date-picker @change="start_time" style="width: 100%" />
                  </a-form-item>
                  <span :style="{ display: 'inline-block', width: '24px', textAlign: 'center' }">
                    -
                  </span>
                  <a-form-item
                          :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }">
                    <a-date-picker @change="end_time" style="width: 100%" />
                  </a-form-item>
                </a-form-item>
              </a-col>
              <a-col span="24">
                <a-form-item label="关键词" :label-col="labelCol" :wrapper-col="wrapperCol">
                  <a-input v-on:keyup="gj_name" placeholder="房号"></a-input>
                </a-form-item>
              </a-col>
          </a-form>
          </a-row>
        </a-modal>
        <a-modal
          title="录入数据"
          v-model="visible"
          @ok="handleOk"
        >
          <a-row>
            <a-form :form="addForm">
              <a-col span="24">
                <a-form-item label="录入项目" :label-col="labelCol" :wrapper-col="wrapperCol">
                     <a-select placeholder="录入项目" @change="TyOnchange" defaultValue="1" >
                      <a-select-option value="1">水电费</a-select-option>
                      <a-select-option value="2">公摊费</a-select-option>
                    </a-select>
                </a-form-item>
              </a-col>
              <a-col span="24">
                <a-form-item label="选择小区\房屋" :label-col="labelCol" :wrapper-col="wrapperCol">
                    <a-cascader :options="options" @change="caOnChange" placeholder="请选择小区\房屋"  v-decorator="['houseIds',{rules:[{required:true,message:'请选择房屋'}]}]"/>
                </a-form-item>
              </a-col>
              <a-col span="24">
                <a-form-item label="开始/结束时间" :label-col="labelCol" :wrapper-col="wrapperCol">
                  <a-range-picker @change="pcOnChange" v-decorator="['datatime',{rules:[{required:true,message:'选择时间'}]}]"/>
                </a-form-item>
              </a-col>
              <a-col span="24">
                <a-form-item label="收费标准" :label-col="labelCol" :wrapper-col="wrapperCol">
                   <a-cascader :options="tollProject" @change="toOnChange" placeholder="请选择收费项目/收费标准"  v-decorator="['toll',{rules:[{required:true,message:'请选择收费项目/收费标准'}]}]"/>
                </a-form-item>
              </a-col>
              <a-col span="24" v-if="addType==1">
                <a-form-item label="起度" :label-col="labelCol" :wrapper-col="wrapperCol">
                  <a-input type="number" v-decorator="['start_key',{rules:[{required:true,message:'请输入开始度数'}]}]"></a-input>
                </a-form-item>
              </a-col>
              <a-col span="24" v-if="addType==1">
                <a-form-item label="止度" :label-col="labelCol" :wrapper-col="wrapperCol">
                  <a-input type="number" v-decorator="['end_key',{rules:[{required:true,message:'请输入结束度数'}]}]"></a-input>
                </a-form-item>
              </a-col>
              <a-col span="24" v-if="addType==1">
                <a-form-item label="倍率" :label-col="labelCol" :wrapper-col="wrapperCol">
                  <a-input type="number" v-decorator="['times',{rules:[{required:true,message:'输入倍率'}],initialValue:1}]"></a-input>
                </a-form-item>
              </a-col>
              <a-col span="24" v-if="addType==2">
                <a-form-item label="公摊" :label-col="labelCol" :wrapper-col="wrapperCol">
                  <a-input type="number" v-decorator="['ratio',{rules:[{required:true,message:'输入公摊费'}]}]"></a-input>
                </a-form-item>
              </a-col>
              <a-col span="24">
                <a-form-item label="备注" :label-col="labelCol" :wrapper-col="wrapperCol" >
                  <a-input v-decorator="['remarks',{rules:[{required:false,message:'输入备注'}],initialValue:''}]"></a-input>
                </a-form-item>
              </a-col>
            </a-form>
          </a-row>
        </a-modal>
      </a-row>
      <br />
      <a-row>
        <s-table
          ref="table"
          :columns="columns"
          :data="dataSource"
          :loading="loading"
        >
          <template slot="remarks" slot-scope="text, record">
            <a-tooltip placement="left">
              <template slot="title">
                <p>{{text}}</p>
              </template>
              <a-icon type="bars" style="cursor: pointer;"></a-icon>
            </a-tooltip>
          </template>
          <template slot="ratio" slot-scope="text, record">
            ¥{{text}}
          </template>
          <a slot="action" slot-scope="text,record" href="javascript:;">
            <a-dropdown :trigger="['click']">
              <a class="ant-dropdown-link" href="#">
                操作
                <a-icon type="down" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item key="0" >
                  <a-popconfirm title="是否要删除此行？" @confirm="deletedItem(record)">
                    <a style="padding-top: 3px">删除</a>
                  </a-popconfirm>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </a>
        </s-table>
      </a-row>
    </a-card>
  </a-row>
</a-spin>
</template>

<script>
import {STable} from '@/components'
import { mapGetters } from 'vuex'
import { search_info, getCashierHouse,getCashierFormulaTwo } from '@/api/cashier'
export default {
    name: 'charge_copy_table_index',
    components: {
      STable
    },
    computed: {
        rowSelection() {
            const { selectedRowKeys } = this
            return {
                onChange: (selectedRowKeys, selectedRows) => {
                    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
                },
                getCheckboxProps: record => ({
                    props: {
                        disabled: record.name === 'Disabled User', // Column configuration not to be checked
                        name: record.name
                    }
                })
            }
        }
    },
    data() {
        return {
            spinning:false,
            confirmLoading:false,
            options1: [],
            data: [],
            proList: [],
            bd_info:[],
            pas:[],
            qu_s:'',
            show_se:false,
            addType:1,
            housesList1:[],
            housesList2:[],
            tollProjectList1:[],
            tollProjectList2:[],
            addForm:this.$form.createForm(this),
            columns: [
              { title: '小区', width: 100 ,dataIndex:'bd_info_id_text'},
              { title: '房号', width: 100 ,dataIndex:'house_id_text'},
              { title: '收费项目', width: 150 ,dataIndex:'project_id_text'},
              { title: '收费标准', width: 150 ,dataIndex:'project_detial_id_text'},
              { title: '开始/结束时间', width: 200 ,dataIndex:'s_e_time'},
              // { title: '单价', width: 150 ,dataIndex:'start_k'},
              { title: '起度', width: 150 ,dataIndex:'start_k'},
              { title: '止度', width: 150 ,dataIndex:'end_k'},
              { title: '倍率', width: 150 ,dataIndex:'times'},
              { title: '费用', width: 150  ,dataIndex:'ratio',align:'right',scopedSlots: { customRender: 'ratio' }},
              // { title: '损耗', width: 150  ,dataIndex:'bd_info_id_text'},
              // { title: '用量', width: 150  ,dataIndex:'bd_info_id_text'},
              { title: '备注', width: 150  ,dataIndex:'remarks',scopedSlots: { customRender: 'remarks' }},
              // { title: '状态', width: 150  ,dataIndex:'status_text'},
              {
                  title: '操作',
                  key: 'operation',
                  fixed: 'right',
                  width: 100,
                  scopedSlots: { customRender: 'action' }
              }
            ],
            visible: false,
            searchVisible: false,
            exportVisible: false,
            pro_det_id: 0,
            houseIds:[],
            options:[],
            tollProject:[],
            house_name_value:'',
            gj_name_value:'',
            start_time_value:'',
            end_time_value:'',
            sf:0,
            bd_id:0,
            pro_id:0,
            baseURL:this.axios.defaults.baseURL,
            loading:false,
            labelCol: {
              xs: { span: 24 },
              sm: { span: 6 },
            },
            wrapperCol: {
              xs: { span: 24 },
              sm: { span: 14 },
            },
            p_dt_id:0,
            // 查询参数
            queryParam: {},
            dataSource:parameter => {
                this.pas = parameter;
              return this.getList(Object.assign(parameter, this.queryParam))
              .then(res => {
                return res
              })
            }
        }
    },
    async mounted() {
        this.getHouse();
        this.getBdList();
        this.getTollProject();
        this.getFormula()
    },
    methods: {
        ...mapGetters(['token', 'pmsArId', 'nowMg']),
        getFormula() {
            getCashierFormulaTwo({token:this.token(),type:1}).then(res => {
                this.options1 = res.data
            }).catch(err => {
                console.log(err)
            })
        },
        selectProject(value) {
            this.p_dt_id = value[1];
        },
        // 获取列表
        getList(param) {
          return new Promise((resolve,reject) => {
            this.axios({
              method:'get',
              url: '/cashier/get_copy_table_list',
              params:Object.assign(param,{token:this.token(),ar_id: this.pmsArId(),cm_mg_id: this.nowMg()})
            }).then(res => {
              if(res.code === 0){
                resolve(res.data)
              }else{
                this.$message.error(res.data.msg,2);
              }
            }).catch(err => {
              this.$message.error('服务器发生错误...',2);
              this.loading = false;
            })
          })
        },
        showModal() {
            this.visible = true
        },
        start_time(date, dateString) {
            this.start_time_value = dateString;
        },
        end_time(date, dateString){
            this.end_time_value = dateString;
        },
        handleOk(e) {
            let _this=this
            this.addForm.validateFields((err, values) => {
              if (err) {
                for(let key in err){
                  for(let item of err[key]['errors']) return this.$message.warning(item['message'],2);
                }
              }
              if(this.addType==1){
                if(!values.houseIds[3]){
                   return this.$message.warning("小区住户选择错误",2)
                }
              }
              values.start_time=values.datatime[0].format('YYYY-MM-DD')
              values.end_time=values.datatime[1].format('YYYY-MM-DD')
              values.addType=this.addType
    
              if(!values.toll[1]){
                 return this.$message.warning("收费标准不正确",2)
              }
              Object.assign(values,{token:this.token()});
              this.spinning = true;
              this.axios({
                method:'post',
                url:'/cashier/add_copy_table',
                data:values,
              }).then(res => {
                this.spinning = false;
                if(res.code == 0){
                  if(_this.addType==1){
                    _this.$message.success(res.msg,2);
                  }else{
                    _this.$message.success(`本次共生成${res.data}条公摊费，生成全部数据需要1分钟，请在1分钟后再去收银台或未缴帐单中查看`,8);
                  }
                  this.$refs.table.refresh(true);
                  this.visible = false
                }else {
                  this.$message.warning(res.msg)
                }
              }).catch(() => {this.$message.error('服务器发生错误...',2),this.spinning = false;});
            })
        },
        handleCancel(e) {
            console.log(e)
            this.visible = false
        },
        searchModal() {
            this.searchVisible = true
        },
        deletedItem(getdata){
          let type=getdata.type
          let id=getdata.id
          this.spinning = true;
          this.axios({
                    method:'post',
                    url: '/cashier/get_copy_table_del',
                    data:{token:this.token(),id:id,type:type}
                }).then(res => {
                    this.spinning = false;
                    if(res.code === 0){
                        this.$message.success(res.msg,2);
                       this.$refs.table.refresh(true);
                    }else{
                        this.$message.error(res.msg,2);
                    }
                }).catch(err => {
                    this.$message.error('服务器发生错误...',2);
                    this.spinning = false;
                })
        },
        searchOk() {
            this.searchVisible = false;
            this.queryParam['cm_mg_id'] = this.nowMg();
            this.queryParam['bd_id'] = this.bd_id;
            this.queryParam['sf'] = this.p_dt_id;
            this.queryParam['start_time'] = this.start_time_value;
            this.queryParam['end_time'] = this.end_time_value;
            this.queryParam['gj_name'] = this.gj_name_value;
            this.queryParam['name'] = '';
            this.house_name_value = '';
            this.$refs.table.refresh(true);
            // return new Promise((resolve,reject) => {
            //     this.axios({
            //         method:'get',
            //         url: '/cashier/get_copy_table_list',
            //         params:Object.assign(Object.assign(this.pas, this.queryParam),{token:this.token(),ar_id: this.pmsArId(),cm_mg_id: this.nowMg(),bd_id:this.bd_id,sf:this.sf,start_time:this.start_time_value,end_time:this.end_time_value,gj_name:this.gj_name_value})
            //     }).then(res => {
            //         if(res.code === 0){
            //             resolve(res.data);
            //             this.searchVisible = false;
            //         }else{
            //             this.$message.error(res.data.msg,2);
            //         }
            //     }).catch(err => {
            //         this.$message.error('服务器发生错误...',2);
            //         this.loading = false;
            //     })
            // })
        },
        searchCancel() {
            this.searchVisible = false
        },
        exportModal() {
          this.exportVisible = true
        },
        exportOk() {
            this.spinning=true;
            this.baseExcDate={pageNo:1,pageSize:10};
            this.exportVisible = false
            let qu = [];
            qu['bd_info_id'] = this.bd_pro_id;
            qu['pro_id'] = this.pro_id;
            qu['pdt'] = this.pro_det_id;
            this.escec(Object.assign(this.baseExcDate, qu))
        },
        export_se_cel(){
            this.show_se = false;
        },
        export_se () {
            let qu = '';
            if (this.gj_name_value) {
                qu = this.gj_name_value;
            } else {
                qu = this.house_name_value;
            }
            let dit = {bd_info_id:this.bd_id,
                start_time:this.start_time_value,
                end_time:this.end_time_value,
                pro_id:this.p_dt_id,
                name:qu};
            this.axios({
                method:'post',
                url:'/cashier/pro_exp_se',
                data:Object.assign(dit,{token:this.token()})
            }).then(res => {
                if(res.code==0){
                    this.show_se = true;
                    this.qu_s = res.msg;
                }else if(res.code==1000){
                    this.spinning=false;
                }else{
                    this.spinning=false;
                    this.show_se = false;
                    this.$message.warning(res.msg,2)
                }
            }).catch(err => {
                this.spinning=false;
                this.$message.error('服务器发生错误...',2);
            }).finally(() => {
                this.loading = false;
            })
        },
        exportOk1() {
            this.spinning=true;
            this.baseExcDate={pageNo:1,pageSize:10};
            this.exportVisible = false;
            let qu = [];
            if (this.gj_name_value) {
                qu['name'] = this.gj_name_value;
            } else {
                qu['name'] = this.house_name_value;
            }
            qu['bd_info_id'] = this.bd_id;
            qu['start_time'] = this.start_time_value;
            qu['end_time'] = this.end_time_value;
            qu['pro_id'] = this.p_dt_id;
            // qu['bd_info_id'] = this.bd_pro_id;
            // qu['pro_id'] = this.pro_id;
            // qu['pdt'] = this.pro_det_id;
            this.escec(Object.assign(this.baseExcDate, qu))
        },
        exportCancel() {
            this.exportVisible = false
        },
        escec(param){
            this.loading = true;
            const _this=this;
            this.axios({
                method:'post',
                url:'/cashier/pro_exp',
                data:Object.assign(param,{token:this.token()})
            }).then(res => {
                if(res.code==0){
                    this.$message.success(`正在生成抄表单请不要刷新页面\n 当前${res.data.pageNo}/${res.data.totalPage}`,2);
                    // if(res.data.totalCount>res.data.pageNo){
                    _this.baseExcDate.pageNo=_this.baseExcDate.pageNo+1;
                    _this.escec(Object.assign(_this.baseExcDate, _this.queryParam))
                    // }
                }else if(res.code==1000){
                    this.spinning=false;
                    window.location.href=this.baseURL+res.url;
                }else{
                    this.spinning=false;
                    this.$message.warning(res.msg,2)
                }
            }).catch(err => {
                this.spinning=false;
                this.$message.error('服务器发生错误...',2);
            }).finally(() => {
                this.loading = false;
            })
        },
        caOnChange(value){
          this.houseIds=value
        },
        pcOnChange(){

        },
        toOnChange(){

        },
        getHouse() {
            getCashierHouse({token:this.token()}).then(res => {
                this.options = res.data
                this.housesList1=res.data
                res.data.forEach((item,key) => {
                  this.housesList2.push({label:item.label,value:item.value})
                });
                if(this.addType==1){
                   this.options =  this.housesList1
                }else{
                    this.options =  this.housesList2
                }
            }).catch(err => {
                console.log(err)
            })
        },
        TyOnchange(value){
          this.addType=value;
          if(value==1){
            this.options =  this.housesList1
            this.tollProject =  this.tollProjectList1
          }else{
            this.options =  this.housesList2
            this.tollProject =  this.tollProjectList2
          }
        },
        detPro(v){
            this.pro_id = this.tollProject[v].value;
            this.proList = this.tollProject[v].children;
        },
        setPro(v){
            this.pro_det_id = this.proList[v].value;
        },
        bdPro(v){
            this.bd_pro_id = this.bd_info[v].id;
        },
        bd_click(v){
            this.bd_id = v;
        },
        sf_click(v){
            this.sf = v;
        },
        gj_name(v){
            this.gj_name_value = v.target.value;
        },
        getBdList(){
            this.axios({
                method:'get',
                url:'/community/get_bd_config_list',
                params:{token:this.token(),ar_id: this.pmsArId(),cm_mg_id: this.nowMg()}
            }).then(res => {
                let { code,msg,data } = res;
                if(code === 0){
                    let ifo = {id:0,name:'所有小区'};
                    data.unshift(ifo);
                    this.bd_info = data;
                }else this.$message.warning(msg);
            }).catch(err => {
                this.$message.error('服务器发生错误...');
            })
        },
        getProList(){
            this.axios({
                method:'get',
                url:'/cashier/get_pro_list',
                params:{token:this.token()}
            }).then(res => {
                let { code,msg,data } = res;
                if(code === 0){
                    this.pro=data
                }else this.$message.warning(msg);
            }).catch(err => {
                this.$message.error('服务器发生错误...');
            })
        },
        // 获取收费标准
      getTollProject() {
        this.axios({
          method:'post',
          url:'/houses/getTollProject_copy',
          data:{token:this.token()}
        }).then(res => {
          this.tollProjectList1=res.data.t1
          this.tollProjectList2=res.data.t2
          if(this.addType==1){
            this.tollProject =  this.tollProjectList1
          }else{
            this.tollProject =  this.tollProjectList2
          }
        }).catch(err => {
          this.$message.error('服务器发生错误...',2);
        })
      },
        onSearch(value) {
            this.queryParam['name'] = value;
            this.house_name_value = value;
            this.queryParam['gj_name'] = '';
            this.queryParam['start_time'] = '';
            this.queryParam['end_time'] = '';
            this.$refs.table.refresh(true);
        },
    }
}
</script>

<style scoped>
</style>